package com.cloudloan.controller;

import com.cloudloan.common.R;
import com.cloudloan.conts.FileConts;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {
    @PostMapping("/upload")
    public R upload(@RequestParam MultipartFile file){
        Map<String,Object> map=new HashMap<>();
        //1.获取上传的文件名
        String fileName = file.getOriginalFilename();
        //2.判断文件后缀名是否为png，jpj
        String substring = fileName.substring(fileName.lastIndexOf("."));
        if (substring.equals(".png")){
            String string = UUID.randomUUID().toString(); //防止文件名重复
            String newFileName = string + substring;
            File newFile=new File(FileConts.IMAGE_PATH+newFileName);
            //3.判断目录是否存在，（不存在的话就创建目录）
            if (!newFile.getParentFile().exists()){
                //创建目录
                newFile.getParentFile().mkdirs();
            }
            //4.复制文件到我们指定的路径下
            try {
                file.transferTo(newFile);
                map.put("fileName",newFileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return R.success(map);
    }
}
